package com.houdoudou.customer.buy;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Order;
import com.houdoudou.bean.Refund;
import com.houdoudou.customer.R;

import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.UniversalHttpPost;

import android.R.bool;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class OrderRefundFrg extends Fragment {

	TextView orderID, refundStateWord,refundResult;
	TextView orderMoney,refundMoney,refundType,refundReason;
	LinearLayout lt_detail;
	ListView stateListView;
	JSONArray statesJA= new JSONArray();
	Button function1,function2,function3;
	private String TIME="time";
	private String AFFAIR="affair";
	private String NOTE="note";
	private String AFFAIR_CANCELREFUND="cancelRefund";
	private String AFFAIR_ARBITRATE="arbitrateRefund";
	StateListAdapter stateListAdapter;
	View.OnClickListener myClickListener;
	ProgressBar  prgs;
	 int refundState=-1;
	 JSONObject refundJO=null;
	 //=OrderDetailAct.orderJO.getInt(Order.STATE);
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.frg_orderrefund, container, false);
		init_listener();
		orderID= (TextView) view.findViewById(R.id.tv_orderid_frgorderrefund);
		refundStateWord= (TextView) view.findViewById(R.id.tv_state_frgorderrefund);
		stateListView= (ListView) view.findViewById(R.id.listview_frgorderrefund);
		refundResult= (TextView) view.findViewById(R.id.tv_refundresult_frgorderrefund);
	//	orderSecret= (TextView) view.findViewById(R.id.tv_secret_frgorderrefund);
		function1= (Button) view.findViewById(R.id.btn_function1_frgorderrefund);
		function2= (Button) view.findViewById(R.id.btn_function2_frgorderrefund);
		function3= (Button) view.findViewById(R.id.btn_function3_frgorderrefund);
		prgs= (ProgressBar) view.findViewById(R.id.prgs_frgorderrefund);
		orderMoney = (TextView) view.findViewById(R.id.tv_ordermoney_frgorderrefund);
		refundType=(TextView) view.findViewById(R.id.tv_refundtype_frgorderrefund);
		refundMoney= (TextView) view.findViewById(R.id.tv_refundmoney_frgorderrefund);
		refundReason=(TextView) view.findViewById(R.id.tv_refundreason_frgorderrefund);
		lt_detail= (LinearLayout) view.findViewById(R.id.lt_refunddetail_frgorderrefund);
		
		prgs.setVisibility(View.GONE);
		function1.setOnClickListener(myClickListener);
		function2.setOnClickListener(myClickListener);
		function3.setOnClickListener(myClickListener);
		stateListAdapter=new StateListAdapter(getActivity());
		stateListView.setAdapter(stateListAdapter);
		return view;		
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		assign_component();
	}

	private void assign_component(){
		System.out.println(" assign_component(); id doing ");
		orderID.setText("订单号："+OrderDetailAct.orderJO.getLong(Order.ID));
		
		boolean isShowCreate=OrderDetailAct.orderJO.getInt(Order.ISREFUND)==1;	//未退款
		isShowCreate= isShowCreate&&(OrderDetailAct.orderJO.getInt(Order.ISMONEYPAID)==2); //Y已支付
	    if(isShowCreate){//不超时
		try{ 
			String dateTimeRDLStr =OrderDetailAct.orderJO.getString(Order.DATETIMERDL);
		        long dateTimeRDL= Long.parseLong(dateTimeRDLStr);
		        isShowCreate=Constant.CURRENT_TIME_SECOND<dateTimeRDL;
		}catch(Exception e){
			isShowCreate=false;	}
	    }
		if(isShowCreate){
				function1.setVisibility(View.VISIBLE);
				function1.setText("申请退款");
				}else{
					function1.setVisibility(View.GONE);	
				}
		if(!OrderDetailAct.orderJO.containsKey("refund")){
			refundStateWord.setText("无退款");
			function2.setVisibility(View.GONE);
			function3.setVisibility(View.GONE);
			refundResult.setVisibility(View.GONE);
			statesJA.clear();
			stateListAdapter.notifyDataSetChanged();
			lt_detail.setVisibility(View.GONE);	
			return;
		}
	
		
		refundJO=OrderDetailAct.orderJO.getJSONObject("refund");
        refundState=refundJO.getInt(Refund.STATE);

		refundStateWord.setText("状态："+CommonFunction.spellRefundStateWord(refundState));
        refundResult.setText("结果："+CommonFunction.spellRefundResultWord(refundJO.getInt(Refund.RESULT)));
        refundResult.setVisibility(View.VISIBLE);
        lt_detail.setVisibility(View.VISIBLE);
        orderMoney.setText("总金额："+OrderDetailAct.orderJO.getDouble(Order.MONEYCU)+"   总数量："+OrderDetailAct.orderJO.getInt(Order.PRODUCTNUM));
        refundMoney.setText("退款金额："+ refundJO.getDouble(Refund.MONEY));
        refundType.setText("退款原因："+CommonFunction.spellRefundTypeWord(refundJO.getInt(Refund.TYPE)) );
        refundReason.setText(refundJO.getString(Refund.REASON));
        
        //千万注意，不能和申请退款搞乱，以下是有退款才执行的，所以不会。
		if(refundJO.getInt(Refund.RESULT)==1){ //退款未结束
			function1.setVisibility(View.VISIBLE);
			function1.setText("修改退款");
			function2.setVisibility(View.VISIBLE);
			function2.setText("取消退款");
		}else{
			function1.setVisibility(View.GONE);
			function2.setVisibility(View.GONE);			
		} 	
		
		//是否显示仲裁
		boolean isArbitrate=refundState==4; //商家拒绝状态下
		
		 if(isArbitrate){
			 try{
		 String dateTimeCLStr= refundJO.getString(Refund.DATETIMECL);
		 long dateTimeCL= Long.parseLong(dateTimeCLStr);
		 isArbitrate=Constant.CURRENT_TIME_SECOND<dateTimeCL;
			 }catch (Exception e){ isArbitrate=false;}
		 }
		 
		 if(isArbitrate){
			 function3.setVisibility(View.VISIBLE);
			 function3.setText("申请系统处理");
		}else {
			function3.setVisibility(View.GONE);
		}
		 
		figureOutState();
		stateListAdapter.notifyDataSetChanged();
	}
	private void init_listener(){
		myClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(v==function1){
					if(!OrderDetailAct.orderJO.containsKey("refund")){ //创建退款
						Intent intent= new Intent(getActivity(), CreateRefundAct.class);
						intent.putExtra("order", OrderDetailAct.orderJO.toString());
						intent.putExtra("affair", "createRefund");
						getActivity().startActivity(intent);
					         return; }
					if(!OrderDetailAct.orderJO.containsKey("refund")) return;
					if(refundJO.getInt(Refund.RESULT)==1){ //修改退款
						Intent intent= new Intent(getActivity(), CreateRefundAct.class);
						intent.putExtra("order", OrderDetailAct.orderJO.toString());
						intent.putExtra("affair", "updateRefund");
						getActivity().startActivity(intent);
					}
				}
				if(v==function2){
					if(refundJO==null) return;
					if(refundJO.getInt(Refund.RESULT)==1){ //取消退款
						String[] params= new String[3];
				         params[0]=Constant.BaseUrl+Constant.CustomerUrl;
				         params[1]=AFFAIR_CANCELREFUND; //PostCod
				         JSONObject jsonData=new JSONObject();
				         jsonData.put("customer", Constant.customerJO);
				         JSONObject refundTempJO= new JSONObject();
				         refundTempJO.put(Refund.ORDERID, refundJO.getLong(Refund.ORDERID));
				         jsonData.put("refund", refundTempJO);
				        params[2]=jsonData.toString();
				      new HttpPostTaskforOrderDo().execute(params);
					}
				}
				if(v==function3){ // 申请仲裁
					if(refundJO==null) return;
					String[] params= new String[3];
			         params[0]=Constant.BaseUrl+Constant.CustomerUrl;
			         params[1]=AFFAIR_ARBITRATE; //PostCod
			         JSONObject jsonData=new JSONObject();
			         jsonData.put("customer", Constant.customerJO);
			         JSONObject refundTempJO= new JSONObject();
			         refundTempJO.put(Refund.ORDERID, refundJO.getLong(Refund.ORDERID));
			         jsonData.put("refund", refundTempJO);
			        params[2]=jsonData.toString();
			      new HttpPostTaskforOrderDo().execute(params);
				}
				
			}
		};
	}
	
	private void figureOutState(){
		statesJA.clear();
		
		 JSONObject stateJO= new JSONObject();stateJO.put(NOTE, "");
		if(refundState>=1){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMECP)); 
			stateJO.put(AFFAIR, "申请退款");  statesJA.add(stateJO); stateJO.put(NOTE, "");
			 }	
		
		if(refundState==2){  
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMES)); 
			stateJO.put(AFFAIR, "商家同意退款");  stateJO.put(NOTE, "");
			statesJA.add(stateJO);
			return; }
		if(refundState==3){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMES)); 
			stateJO.put(AFFAIR, "退款成功");   stateJO.put(NOTE, "系统处理");
			statesJA.add(stateJO);
			return; }
		if(refundState>=4&&(!refundJO.getString(Refund.DATETIMES).isEmpty())){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMES)); 
			stateJO.put(AFFAIR, "商家拒绝退款");  stateJO.put(NOTE, "");
			statesJA.add(stateJO);
			 }
		if(refundState==5){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMEC)); 
			stateJO.put(AFFAIR, "退款失败");  stateJO.put(NOTE, "系统处理");
			statesJA.add(stateJO); 
			return;}
		if(refundState>=6&&(!refundJO.getString(Refund.DATETIMEC).isEmpty())){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMEC)); 
			stateJO.put(AFFAIR, "申请仲裁");  stateJO.put(NOTE, "");
			statesJA.add(stateJO); 
			 }
		if(refundState==7){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMEO)); 
			stateJO.put(AFFAIR, "仲裁同意退款");  stateJO.put(NOTE, "");
			statesJA.add(stateJO); 
			return; }
		if(refundState==8){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMEC)); 
			stateJO.put(AFFAIR, "仲裁拒绝退款");  stateJO.put(NOTE, "");
			statesJA.add(stateJO); 
			 return; }
		if(refundState==9){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMEC)); 
			stateJO.put(AFFAIR, "退款成功");   stateJO.put(NOTE, "系统处理");
			statesJA.add(stateJO); 
			return; }
		
		if(refundState==10){
			stateJO.put(TIME, refundJO.getString(Refund.DATETIMECC)); 
			stateJO.put(AFFAIR, "取消退款");   stateJO.put(NOTE, "");
			statesJA.add(stateJO); 
			return; }
		
	}
	
	
class StateListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    private int parentPosition;
	        public StateListAdapter(Context context) {
				
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		  
		}


	    final class Zujian{  
	         public TextView time,affair; 
	       
	      
	        }  
	          @Override
	       public int getCount() {
		// TODO Auto-generated method stub
		    return statesJA.size();  
	        	 
	       }

	      @Override
	       public Object getItem(int position) {
		// TODO Auto-generated method stub
		       return statesJA.getJSONObject(position);  
	    	 
	          }

	    @Override
	     public long getItemId(int position) {
		// TODO Auto-generated method stub
		       return position; 
	       }

	               @Override
	    public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int childID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_orderstate, null);              
	            zj.time=(TextView) convertView.findViewById(R.id.tv_time_list_frgorderstate);
	            zj.affair=(TextView) convertView.findViewById(R.id.tv_affair_list_frgorderstate);
	            convertView.setTag(zj);  
	            System.out.println("position----"+position+"------inflated");
	        }else{   System.out.println("position----"+position+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  		        						  
	        //绑定数据  
	        zj.time.setText(statesJA.getJSONObject(childID).getString(TIME));
	        zj.affair.setText(statesJA.getJSONObject(childID).getString(AFFAIR));
	       
	        
	   //     imageLoader.showImageAsyn(zj.img, record.getString(Product.DIR), R.drawable.p3);       
	        return convertView;
	       } 
	         }// end Adapter

	
	

private  class HttpPostTaskforOrderDo extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
				
			 System.out.println("-----------onPostExecute()--------------");
			 prgs.setVisibility(View.GONE);
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 CommonFunction.alert(getActivity(), "失败", "无网络连接");return;
		      
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
			    JSONObject json = null;
			    int resultCode=-1;
				String resultInfo="";
				String affair="";				
				JSONObject jo;
				try{
			     json= JSONObject.fromObject(PostResult);
			     resultCode=json.getInt("resultCode");
			     resultInfo=json.getString("resultInfo");	
			     affair =json.getString("affair");	
			     jo= json.getJSONObject("jo");
				}catch(JSONException e){
					 CommonFunction.alert(getActivity(), "失败", "数据解析错误");return;
				}
				
				if(resultCode==2||resultCode==3){ //表示回传了更新订单
			    	   JSONObject  orderJOOnline=jo.getJSONObject("order");		
			    	   Intent intent = new Intent(ChoosePayAct.ACTION_ORDER_CHANGED);  
					   intent.putExtra("order", orderJOOnline.toString());  
					   getActivity().sendBroadcast(intent);   }
				 if(resultCode==2){ //成功
					//  Toast.makeText(getActivity(), "成功", Toast.LENGTH_SHORT).show();  
			    	  try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
					 CommonFunction.alert(getActivity(), "成功", "取消订单成功");  
					 assign_component();
				 }
				 if(resultCode==1||resultCode==3){ //失败
			    	   CommonFunction.alert(getActivity(), "失败", resultInfo); 
			    	   if(resultCode==3){  assign_component();} 
			       }  
		       
			
		} //onPostExecute
	} //AsyncTask
	
}
